<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\OrderLease;
use App\Models\ShopSms;
use App\Models\SmsRecord;
use App\Models\SmsTemplate;
use App\Services\OrderService;
use Illuminate\Console\Command;

class RepaymentReminderCommand extends BaseCommand
{

    const LIMIT_DAY = 1;//提前几天发送还款短信提醒
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'repaymentReminder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '还款提醒';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {
        try {
            $day = self::LIMIT_DAY;
            $begin_time = strtotime(date('Y-m-d 00:00:00',strtotime("+$day day")));
            $end_time = strtotime(date('Y-m-d 23:59:59',strtotime("+$day day")));


            $where1[] = ['create_time','>=', date('Y-m-d 00:00:00')];
            $where1[] = ['create_time','<=', date('Y-m-d 23:59:59')];
            $where1[] = ['template_id',SmsTemplate::SMS_TEMPLATE_REPAYMENT_REMINDER];
            $countpluck = SmsRecord::where($where1)->distinct('order_id')->pluck('order_id');

            $where = [
                ['ol.begin_time','>=',$begin_time],
                ['ol.begin_time','<=',$end_time],
                ['ol.status',OrderLease::ORDER_LEASE_STATUS_NOPAY],
            ];
            //数据
            $data = obToArray(Order::from('sp_order_2 as o')
//                ->where('o.seller_id',1704471738)
                ->select('o.seller_id','o.trade_no','ol.id','m.user_id','ol.id','m.mobile','ol.which_period','ol.rent','ol.begin_time')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id','ol.order_id')
                ->leftjoin('sp_member_2 as m','o.uid','m.id')
                ->whereIn('o.status',OrderService::getOrderStatus(OrderService::ORDER_OVERDUE_COUNT))
                ->where($where)
                ->whereNotIn('o.trade_no',$countpluck)
                ->orderBy('ol.id', 'desc')
                ->get());
//            var_dump($data);exit();
            foreach ($data as $item){
                if($item['rent'] > 0){
                    //发送短信
                    $res = ShopSms::repaymentReminder($item['seller_id'],$item['mobile'],$item['which_period'],$item['rent'],$item['trade_no'],$item['id'],date('Y-m-d H:i:s',$item['begin_time']),$item['user_id']);
//              dd($res);
                }
            }
            $this->infoLog('还款提醒发送短信执行成功',$data);
        }catch (\Exception $exception){
            $this->infoLog('还款提醒发送短信执行失败'.$exception->getMessage());
        }
    }
}
